﻿/**
 * v 1.1
 *
 * 2020.4.21 修改播放图标 修改标题文字样式
 * 2020.4.24 将视频配置节点文件单独剔除到manifest.js 中
 *
 */
var globalWxApi = 'https://test.nanme.top/api/';
/* 此接口需要两个功能.
1: 微信jssdk 签名认证. 数据部分为.post {debug:bool,url:string},
2: 语音测评: 分两种.
                  1: 需要下载,例如微信 参数如下:
                                              post wx:{
                                                        audioUrl:音频文件下载完整连接.
                                                        param:{
                                                                request:{
                                                                  refText: String,
                                                                  precision: String,
                                                                  rank: int,
                                                                  tokenId:String
                                                                },
                                                                audio: {
                                                                  audioType: string 'wav/mp3/amr...',
                                                                  sampleRate: int,
                                                                  channel: 1,
                                                                  sampleBytes:2
                                                                }
                                                        }
                                                  }
                      返回 result 另增加 公众号token 用来生成下载链接.
                  2: 无需下载,直接传递文件: param部分与 需要下载的一致. form表单单另增加 一个 audio 头为 二进制文件数据,且参数以 post流形式提交.
*/

var globalUserID = 'testUserID'; // 用户评测id
var progressBar = 1; //隐藏进度条
var globalTmp = {
  last: 0,
  time: 0,
  check: 0
}
var firstClick = false;
var wxCon = {};
var weChatIOS = {
  /*
   * 获取微信mediaId
   */
  mediaId: '',
  localId: '',
  token: '',
  isRecord: false,
  fc: 'hf',
  weConfig: function () {
    var WXconfig = {
      debug: false,
      url: location.href.split('#')[0]
    }
    $.ajax({
      // url: "https://static.4ukids.cn/app/getMpSign", //调用后台获取签名以及一些必要信息
      url: globalWxApi, //调用后台获取签名以及一些必要信息
      type: "post",
      dataType: "json",
      cache: false,
      data: WXconfig,
      success: function (r) {
        if (typeof r.debug == 'undefined') r.debug = WXconfig.debug;
        if (typeof r.token == 'undefined') r.token = r.accessToken;
        weChatIOS.token = r.token
        wxCon = {
          debug: r.debug,
          appId: r.appId,
          timestamp: r.timestamp,
          nonceStr: r.nonceStr,
          signature: r.signature,
          jsApiList: [
            'startRecord',
            'stopRecord',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'onVoicePlayEnd',
            'uploadVoice',
            'checkJsApi',
            'getLocalImgData'
            // 'translateVoice',
            // 'scanQRCode',
            // 'openCard'
          ]
        };
        wx.config(wxCon);
        wx.ready(function () {
          console.log('微信jssdk成功', r);
        });
        wx.error(function (res) {
          console.log('微信jssdk失败', res, wxCon, r);
        });
      }
    })
  },
  /*
   * 开始录音
   */
  startRecord: function () {
    wx.ready(function () {
      wx.startRecord({
        success: function () {
          weChatIOS.onRecord();
        },
        fail: function (res) {
          console.log('微信开启录音失败', res);
        },
        cancel: function () {
          console.log('微信拒绝授权');
        }
      });
    });
  },
  /*
   * 结束录音api
   */
  onStopRecord: function () {
    if (weChatIOS.isRecord) weChatIOS.isRecord = false;
    else return;
    wx.stopRecord({
      fail: function (res) {
        console.log('微信 停止录音失败', res);
      },
      success: function (resStop) {
        console.log('微信 停止录音成功', resStop.localId);
        weChatIOS.localId = resStop.localId;
        wx.uploadVoice({
          localId: weChatIOS.localId,
          isShowProgressTips: 0,
          success: function (res) {
            weChatIOS.mediaId = res.serverId;
            console.log('微信 上传 成功');
            weChatIOS.evalResult();
          },
          fail: function (res) {
            console.log('微信 上传 失败', res, resStop, weChatIOS.localId);
          }
        });
      }
    });
  },
  /*
   * 结束录音
   */
  stopRecord: function () {
    // clearTimeout(weChatIOS.onRecordId);
    weChatIOS.onStopRecord();
  },
  /*
   * 监听回放
   */
  onRecord: function () {
    var time = defaultTime(videosObj.markers[videosObj.nowObj].refText) + 1000;
    weChatIOS.isRecord = true;
    weChatIOS.onRecordId = setTimeout(
      "weChatIOS.onStopRecord()", time);
  },
  /*
   * 开始回放
   */
  startPlay: function () {
    if (weChatIOS.localId) {
      wx.ready(function () {
        wx.playVoice({
          localId: weChatIOS.localId,
        });
        wx.onVoicePlayEnd({
          success: function (res) {
          }
        });
      });
    } else {
      console.log('微信 回放 没有发现localId');
    }
  },
  /*
   * 监听停止回放
   */
  onStopPlay: function () {
    wx.stopVoice({
      localId: weChatIOS.localId,
    });
  },
  /*
   *结束回放
   */
  stopPlay: function () {
    wx.ready(function () {
      weChatIOS.onStopPlay();
    });
  },
  evalResult: function (result) {
    var sData = {
      'audioUrl': 'https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' + weChatIOS.token + '&media_id=' + weChatIOS.mediaId,
      'param': {
        request: videosObj.markers[videosObj.nowObj],
        audio: {
          audioType: "amr",
          sampleRate: 8000,
          channel: 1,
          sampleBytes: 2
        },
        userId: globalUserID
      },
    };
    $.ajax({
      type: "POST",
      url: globalWxApi,
      data: { wx: sData },
      dataType: 'json',
      success(data) {
        console.log('收到数据', data);
        videosObj.myRecordResult(data);
      },
      error(e) {
        console.log('错误', e);
      }
    });
  },
}
var nativeIOS = {
  setupWebViewJavascriptBridge: function (callback) { //调用app方法
    if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
    if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'https://__bridge_loaded__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
  },
  startRecord: function (params, callback) { //开始录音
    nativeIOS.setupWebViewJavascriptBridge(function (bridge) {
      /* Initialize your app here */
      var data = { content: params.refText }
      if (params.coreType == 'en.word.score') {
        data.type = '0'
      } else if (params.coreType == 'en.sent.score') {
        data.type = '1'
      }
      bridge.callHandler('Native_StartRecord', data, function responseCallback(responseData) {
        console.log("js 调用接口录音")
      });
      bridge.registerHandler('JS_ResponseEvaluateResult', function (res, responseCallback) {
        console.log("JS_ResponseEvaluateResult called with:", res)
        callback(res)
        responseCallback(res)
      })
    })
  },
  stopRecord() {
  },
  playRecordFile: function () {
    nativeIOS.setupWebViewJavascriptBridge(function (bridge) {
      /* Initialize your app here */
      bridge.callHandler('Native_PlayRecordFile', function responseCallback(responseData) {
        console.log("js 调用接口播放录音")
      });
    })
  }
}
// 安卓方法
var nativeAndroid = {
  // 开始录音
  startRecord: function (params) {
    var data = { content: params.refText }
    if (params.coreType == 'en.word.score') {
      data.type = '0'
    } else if (params.coreType == 'en.sent.score') {
      data.type = '1'
    }
    // 调用安卓app方法
    justTest.Native_StartRecord(data.type, data.content)
  },
  // 停止录音
  stopRecord: function (errorCode, overallScore, msg) {
    // js逻辑处理
    if (Number(errorCode)) {
      videosObj.myRecordResultfail();
    } else {
      var dd = {
        result: {
          overall: overallScore
        }
      }
      videosObj.myRecordResult(dd)
    }
  },
  // 播放
  playRecordFile: function () {
    // 调用安卓app方法
    justTest.Native_PlayRecordFile()
  }
}
// U3D方法
var nativeU3D = {
  // 开始录音
  startRecord: function (params) {
    console.log('u3d startRecord = ', params)
    var data = { content: params.refText }
    if (params.coreType == 'en.word.score') {
      data.type = '0'
    } else if (params.coreType == 'en.sent.score') {
      data.type = '1'
    }
    // 调用U3D方法
    window.location.href = "uniwebview://U3D_StartRecord?type=" + data.type + "&content=" + data.content;
  },
  // 停止录音
  stopRecord: function (errorCode, overallScore, msg) {
    // js逻辑处理
    if (Number(errorCode)) {
      videosObj.myRecordResultfail();
    } else {
      var dd = {
        result: {
          overall: overallScore
        }
      }
      videosObj.myRecordResult(dd)
    }
  },
  // 播放
  playRecordFile: function () {
    // 调用安卓U3D方法
    window.location.href = "uniwebview://U3D_PlayRecordFile";
  },
  // 点击停止录音
  stopClickRecord: function () {
    // 调用安卓U3D方法
    window.location.href = "uniwebview://U3D_StopRecord";
  },
}
var videosObj = {
  markers: makers,
  myPlayer: null, //videos对象
  duration: null, //总时长
  timer1: null,
  myRecord: null,
  nowObj: null,
  isApp: isApp(),
  questionType: function (obj) { //处理题型
    // console.log('开始处理题型', obj);
    this.maskShow();
    if (obj.type == 'audio2img') {
      this.audio2img(obj);
    } else if (obj.type == 'audio2audio') {
      this.audio2audio(obj);
    } else if (obj.type == "audio2touch") {
      this.audio2touch();
    } else if (obj.type == 3) {
      this.type3(obj);
    } else if (obj.type == 6) {
      this.type6(obj);
    } else if (obj.type == 4) {
      this.type4(obj);
    } else if (obj.type == 7) {
      this.type7(obj);
    }
  },
  //------------------------------------------------------------------------------提问类型  audio2img 题型2
  audio2img: function (obj) {
    var content = $('<div class="content">')
    // if (obj.type == 'audio2img') {
    //     content.addClass('img-big')
    // }
    var _this = this
    var audio = $(`<audio preload="auto" class="quAudio" src="${obj.question}">`)
    var divTitle = $("<div class='qu-title'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`)
    content.append(divTitle)
    var divC = $("<div class='qu-body'>")
    for (var i = 0; i < obj.answers.length; i++) {
      var item = obj.answers[i]
      var d = `
            <div class='answer-item' >
                <img class="answerimg" style="display:none" src="${obj.answer == i ? './img/rit.png?38' : './img/err.png?36'}" />
              <img an-id="${i}" class="answer-item-hook" src="${item.img}" />
              <div>${item.text || ''}</div>
              <div>${item.sub || ''}</div>
            </div>
          `
      divC.append(d)
    }
    content.append(divC)
    content.append(`
        <div class="next-wrapp ">
        <div class="footer-item next-hook" style="display:none"> <div class='next' ></div><!--<div class="text">继续</div>--></div>
          </div>
        `)
    $('.mask').append(content)
    //点击播放题目
    $('.playAudio').on('click', function () {
      audio[0].play()
    })
    // 给每个选项添加点击
    $(".answer-item-hook").on("click", function () {
      var that = this
      var i = $(this).attr('an-id')
      $(this).siblings(".answerimg").hide()
      $(this).siblings(".answerimg").show()
      if (i == obj.answer) {
        _this.answerRight(true)
      } else {
        _this.answerErr()
        setTimeout(function () {
          $(that).siblings(".answerimg").hide()
        }, 1000)
      }
    })
    $(".next-hook").on('click', function () {
      _this.goOn()
    });
    checkImgSize();
  }, //-----------------------------------------------------------------------------提问类型  audio2img END
  //------------------------------------------------------------------------------提问类型  audio2audio 题型1
  isRecord: 1,
  audio2audio: function (obj) {
    this.isRecord = 1
    var audio = $(`<audio preload="auto" src="${obj.question}">`)
    var _this = this
    var content = $('<div class="content audio-item">')
    var divTitle = $("<div class='qu-title'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`)
    content.append(divTitle)
    var divC = $("<div class='qu-body'>")
    if (obj.img) {
      divC.append(`<div class='safdsa'><img class='checkImgSize' src='${obj.img}'/></div>`)
    } else {
      divC.append(`<div style="height:2rem"></div>`)
    }
    content.append(divC)
    content.append(`<div class="next-wrapp next-hook"><button class="record ">
        <img class="record-icon" src="./img/record.png" /></div>`)
    // content.append(`<div class="next-wrapp"><button class="record "><div class="re-out"><div class="re-inner"></div></div><div class="btn-lable">正在录音</div></button></div>`)
    $('.mask').html(content)
    //点击播放题目
    $(".record").on('click', function () {
      // console.log($('.playAudio'));
      $('.playAudio').attr("disabled", true);
      if (_this.isRecord == 1) {
        _this.recordFun(obj)
        // _this.isRecord = -1
      } else if (_this.isRecord == -1) {
        _this.stopRecordFun()
        _this.isRecord = 0
      }
    })
    $('.playAudio').on('click', function () {
      // $(this).attr("dis")
      audio[0].play()
    });
    // console.log(466);
    checkImgSize();
  }, //-----------------------------------------------------------------------------提问类型  audio2audio END
  //------------------------------------------------------------------------------提问类型   题型3
  type3: function (obj) {
    var audio = $(`<audio preload="auto" src="${obj.question}">`)
    var audio0 = $(`<audio preload="auto" src="${obj.answers[0].mp3}">`)
    var audio1 = $(`<audio preload="auto" src="${obj.answers[1].mp3}">`)
    var audio2 = $(`<audio preload="auto" src="${obj.answers[2].mp3}">`)
    var _this = this
    var content = $('<div class="content audio-item">')
    var divTitle = $("<div class='qu-title'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio playAudio1"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`)
    content.append(divTitle)
    var divC = $("<div class='qu-body'>")
    if (obj.img) {
      divC.append(`<div class='safdsa'><img class='checkImgSize' src='${obj.img}'/></div>`)
    } else {
      divC.append(`<div style="height:2rem"></div>`)
    }
    content.append(divC)
    var divD = $(`<div class = 'type3options'>
                        <div class ='option'>
                            <div class = 'option0music options'></div>
                            <div an-id="0" class = 'option0buttom buttom'>
                            <img src="./img/df-o.png"></img>
                            <img class="answerimg" style="display:none" src="${obj.answer == 0 ? './img/rit1.png?38' : './img/err1.png?36'}" /></div>
                        </div>
                        <div class ='option'>
                            <div class = 'option1music options'></div>
                            <div an-id="1" class = 'option1buttom buttom'>
                            <img src="./img/df-o.png"></img>
                            <img class="answerimg" style="display:none" src="${obj.answer == 1 ? './img/rit1.png?38' : './img/err1.png?36'}" /></div>
                        </div>
                        <div class ='option'>
                            <div class = 'option2music options'></div>
                            <div an-id="2" class = 'option2buttom buttom'>
                            <img src="./img/df-o.png"></img>
                            <img class="answerimg"  style="display:none" src="${obj.answer == 2 ? './img/rit1.png?38' : './img/err1.png?36'}" /></div>
                        </div>
                    </div>`)
    content.append(divD)
    content.append(`
        <div class="next-wrapp" style="display:none">
        <div class="footer-item next-hook" style="margin-top:0"> <div class='next' ></div><!--<div class="text">继续</div>--></div>
          </div>
        `)
    $('.mask').html(content)
    //点击播放题目
    $('.playAudio1').on('click', function () {
      audio[0].play()
    })
    $('.option0music').on('click', function () {
      audio0[0].play()
    })
    $('.option1music').on('click', function () {
      audio1[0].play()
    })
    $('.option2music').on('click', function () {
      audio2[0].play()
    })
    // 给每个选项添加点击
    $(".buttom").on("click", function () {
      var that = this
      var i = $(this).attr('an-id')
      $(this).find(".answerimg").hide()
      $(this).find(".answerimg").show()
      if (i == obj.answer) {
        $('.type3options').hide()
        _this.answerRight()
      } else {
        _this.answerErr()
        setTimeout(function () {
          $(that).find(".answerimg").hide()
        }, 1000)
      }
    })
    $(".next-hook").on('click', function () {
      _this.goOn()
    });
    checkImgSize();
  },
  //------------------------------------------------------------------------------提问类型   题型4
  type4: function (obj) {
    var audio = $(`<audio preload="auto" src="${obj.question}">`)
    var _this = this
    var content = $('<div class="content audio-item">')
    var divTitle = $("<div class='qu-title'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`)
    content.append(divTitle)
    var divC = $("<div class='qu-body'>")
    if (obj.img) {
      divC.append(`<div class='safdsa'><img class='checkImgSize' src='${obj.img}'/></div>`)
    } else {
      divC.append(`<div style="height:2rem"></div>`)
    }
    content.append(divC)
    content.append(`
        <div class="next-wrapp">
        <div an-id="${obj.isTrue}" an="1" class="yes yesno"><img src='./img/Yes.png'>
        <img class="answerimg" style="display:none" src="${obj.isTrue == 1 ? './img/rit1.png?38' : './img/err1.png?36'}" /></div>
        <div class="yn"></div>
        <div an-id="${obj.isTrue}" an="0" class="no yesno"><img src='./img/No.png'>
        <img class="answerimg" style="display:none" src="${obj.isTrue == 0 ? './img/rit1.png?38' : './img/err1.png?36'}" />
        </div>
        </div>`)
    content.append(`
        <div class="next-wrapp" style="display:none">
        <div class="footer-item next-hook" > <div class='next' ><!--</div><div class="text">继续</div>--></div>
          </div>
        `)
    $('.mask').html(content)
    $('.playAudio').on('click', function () {
      audio[0].play()
    })
    // 给每个选项添加点击
    $(".yesno").on("click", function () {
      var that = this
      var i = $(this).attr('an-id')
      var b = $(this).attr('an')
      if (i == b) {
        $(this).parent().hide();
        $(this).find(".answerimg").show();
        _this.answerRight();
      } else {
        _this.answerErr()
        $(this).find(".answerimg").show()
        setTimeout(function () {
          $(that).find(".answerimg").hide()
        }, 1000)
      }
    })
    $(".next-hook").on('click', function () {
      _this.goOn()
    });
    checkImgSize();
  },
  //------------------------------------------------------------------------------提问类型   题型6
  type6: function (obj) {
    var audio = $(`<audio preload="auto" src="${obj.question}">`)
    var _this = this
    var content = $('<div class="content audio-item">')
    var divTitle = $("<div class='qu-title'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`)
    content.append(divTitle)
    var divC = $("<div class='qu-body' >")
    if (obj.img) {
      divC.append(`<div class='safdsa'><img class='checkImgSize' src='${obj.img}'/></div>`)
    } else {
      divC.append(`<div style="height:2rem"></div>`)
    }
    content.append(divC)
    // content.append(`<div class="next-wrapp next-hook" style="display:block">
    // <div class="text-option">
    //     1 apple
    //         <img an-id="${i}" class="answerimg" style="" src="${obj.answer == 0 ? './img/rit.png?38' : './img/err.png?36'}" />
    // </div>
    // <div class="text-option">2 apples</div>
    // <div class="text-option">3 apples</div>
    // </div>`)
    // content.append(`<div class="next-wrapp next-hook" style="display:block">`)
    var d = `<div class="xac">`
    for (var i = 0; i < obj.text.length; i++) {
      var item = obj.text[i]
      var d = d + `
            <div  an-id="${i}" class="text-option btn-bg-yellow">
            ${item}
                <img class="answerimg" style="display:none" src="${obj.answer == i ? './img/rit1.png?38' : './img/err1.png?36'}" />
            </div>
          `
    }
    d = d + `</div>`
    content.append(d)
    content.append(`</div>`)
    content.append(`
        <div class="next-wrapp" style="display:none">
        <div class="footer-item next-hook" style="margin-top:0"> <div class='next' ></div></div>
          </div>
        `)
    $('.mask').html(content)
    $('.playAudio').on('click', function () {
      audio[0].play()
    })
    // 给每个选项添加点击
    $(".text-option").on("click", function () {
      var that = this
      var i = $(this).attr('an-id')
      $(this).find(".answerimg").show()
      if (i == obj.answer) {
        $(this).parent().hide();
        _this.answerRight()
      } else {
        _this.answerErr()
        setTimeout(function () {
          $(that).find(".answerimg").hide()
        }, 1000)
      }
    })
    $(".next-hook").on('click', function () {
      _this.goOn()
    });
    checkImgSize();
  },
  //-------------------------------------------------------------------------------提问类型 audio2touch 题型5
  //------------------------------------------------------------------------------提问类型  7
  type7: function (obj) {
    let mask = $('.mask');
    var content = $('<div class="content type7">');
    var _this = this
    var audio = $(`<audio preload="auto" class="quAudio" src="${obj.question}">`)
    var divTitle = $("<div class='title7 x jc wf'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`)
    // content.append(divTitle);
    mask.append(divTitle);
    var divC = $("<div class='qu-body'>");
    let item = 0;
    let s = 0;
    let spacing = `<div style="width:${obj.spacing};">`;
    for (var i = 0; i < obj.answers.length; i++) {
      item = obj.answers[i];
      if (!item.imgStyle) item.imgStyle = '';
      if (!item.pStyle) item.pStyle = '';
      t = $(`<div class="answer-item" style="flex-grow:0;${item.pStyle}">`);
      t.append(`<img class="answer-item-hook imgB" src="${item.img}" style="${item.imgStyle}"/>`);
      if (item.right) {
        if (typeof item.right == 'string') s = item.right; else s = '';
        // t.append('<img class="rit3" style="display:none;' + s + '" src="./img/rit2.png" />');
        t.on("click", (param) => {
          let o = $(param.currentTarget)
          type7right(o, () => {
            // $('.content').css('overflow', 'visible');
            t = o.children();
            // o.css('position', 'relative');
            // t.eq(1).width(t.eq(0).width());
            $('.rit3').show();
            if (t.length > 1) t[1].play();
            // o.width(t.width());
            o.css('flex-grow', '0');
            // o.css('max-width');
            if (item.pStyle) {
              o.attr('style', o.attr('style') + item.pStyle);
            }
            setTimeout(() => {
              _this.goOn();
            }, 2000);
          });
        });
      } else {
        t.on("click", (param) => {
          let o = $(param.currentTarget);
          type7err(o, () => {
            // console.log(o);
            // o.css('flex-grow', '1');
            t = o.children();
            if (t.length > 1) t[1].play();
          });
        });
      }
      if (item.audio) t.append(`<audio preload="auto" class="quAudio" src="${item.audio}">`);
      divC.append(t);
      if (obj.answers.length - 1 - i) divC.append(spacing);
    }
    // divC.append('<div>');
    content.append(divC);
    mask.append(content);
    mask.append('<img class="rit3" style="display:none;' + s + '" src="./img/rit2.png" />');
    //点击播放题目
    $('.playAudio').on('click', function () {
      audio[0].play()
    });
    // t.children()[0].onload = function () {
    //   if (divC.height() < t.height()) divC.children().css('height', '100%');
    // }
    // console.log();
    // t.resize(()=>{
    //   console.log(t.height());
    // });
    $(".next-hook").on('click', function () {
      _this.goOn();
    });
    ImgHf();
  }, //-----------------------------------------------------------------------------提问类型  7 END
  audio2touch: function () {
    var obj = this.markers[this.nowObj];
    var _this = this;
    var audio = $(`<audio preload="auto" src="${obj.question}">`);
    var content = $('<div class="content audio-item">');
    var divTitle = $("<div class='qu-title'>");
    var t = "";
    if (obj.title && obj.title.title) {
      if (obj.title.style) t = 'style="' + obj.title.style + '"';
      obj.title = obj.title.title;
    }
    divTitle.append(`<button class="playAudio"><img src="./img/laba.png" /></button><div class="title-b" ${t}>${obj.title ? obj.title : ''}</div>`);
    content.append(divTitle);
    var divC = $("<div class='qu-body' >");
    var touchW = $("<div class='touch-wrapp2'>");
    touchW.append(`<img id='touchbg'  src='${obj.answers.img}'>`);
    touchW.append(`<img class="answerimg err" style="display:none;${obj.errorStyle ? obj.errorStyle : ''}" src="./img/err.png" />`);
    // touchW.append(`<img class="answerimg rit" style="display:none" src="./img/rit.png?38" /><img class="answerimg err" style="display:none" src="./img/err.png?36" />`)
    var area = obj.area
    for (var i = 0; i < area.length; i++) {
      var di = $("<div class='area-item answer-item-hook' isRit=" + area[i].isTrue + ">")
      var d2 = $("<div class='area-item answer-item-hook' isRit=" + area[i].isTrue + ">");
      di.css({
        width: area[i].width + '%',
        height: area[i].height + '%',
        top: area[i].top + '%',
        left: area[i].left + '%',
        transform: `rotate(${area[i].rotate || 0}deg)`,
        // '-ms-transform': 'rotate(7deg)', 	/* IE 9 */
        // '-moz-transform': 'rotate(7deg)', 	/* Firefox */
        // '-webkit-transform': 'rotate(7deg)', /* Safari 和 Chrome */
        // '-o-transform': 'rotate(7deg)'
      });
      d2.css({
        width: area[i].width + '%',
        height: area[i].height + '%',
        top: area[i].top + '%',
        left: area[i].left + '%'
      });
      d2.append(`<img class="answerimg rit" style="display:none" src="./img/rit.png" />`)
      touchW.append(d2);
      touchW.append(di);
    }
    var d2 = $("<div class='touch-wrapp'>")
    d2.append(touchW)
    divC.append(d2)
    content.append(divC)
    content.append(`
        <div class="next-wrapp" style="
        width: 100%;
        bottom: 5%;">
        <div class="footer-item next-hook" style='display:none'> <div class='next' ></div></div>
          </div>
        `)
    $('.mask').html(content)
    $(".answer-item-hook").on("click", function () {
      var that = this
      var ist = $(this).attr("isRit")
      if (ist == "1") {
        $('.rit').show()
        _this.answerRight()
        $(".next-hook").show()
        // setTimeout(function () {
        //   _this.goOn()
        // }, 1500)
      } else {
        _this.answerErr()
        $(that).siblings(".err").show()
        setTimeout(function () {
          $(that).siblings(".err").hide()
        }, 500)
      }
    })
    $("#touchbg").on("click", function () {
      var that = this
      _this.answerErr()
      $(that).siblings(".err").show()
      setTimeout(function () {
        $(that).siblings(".err").hide()
      }, 500)
    })
    $('.playAudio').on('click', function () {
      audio[0].play()
    })
    $(".next-hook").on('click', function () {
      _this.goOn()
    });
    checkImgSize();
  }, //-------------------------------------------------------------------------------提问类型 audio2touch END
  randArr(arr) {
    var n = Math.floor(Math.random() * arr.length + 1) - 1;
    return arr[n]
  },
  rigthAudio: [
    "#greatAudio",
    "#excelentAudio",
    "#goodjobAudio"
  ],
  answerRight: function (current = false) { //回答正确
    $(this.randArr(this.rigthAudio))[0].play()
    // 回答正确移除点击事件
    $(".answer-item-hook").unbind("click");
    $(".text-option").unbind("click");
    $(".yesno").unbind("click");
    $("#touchbg").unbind("click");
    $(".option .buttom,.option .options").unbind("click");
    if (current) {
      $(".next-hook").show();
    } else {
      $(".next-hook").parent().show();
    }

  },
  answerErr: function () { //回答错误
    $("#tryaginAudio")[0].play()
    // this.dialog("err")
  },
  maskShow: function () {
    $(".mask").show()
  },
  maskHide: function () {
    $(".mask").hide()
  },
  // 继续播放视频--------------------------------------------------------------next
  goOn: function () {
    this.maskHide()
    $(".mask").html('')
    this.myPlayer.play()
    this.markers[this.nowObj].timecuo = new Date().getTime()
  },
  //--------------------------------------------------------------------------加入卡点到时间轴
  addMarkers: function () { //添加节点
    var t = this.myPlayer.cache_.duration;
    if (!this.duration) {
      if (!this.myPlayer.cache_.duration) {
        setTimeout(() => {
          this.addMarkers();
        }, 100);
        return;
      }
      this.duration = this.myPlayer.cache_.duration;
    }
    // console.log('添加节点:', this.duration);
    var _this = this
    var markers = this.markers;
    // console.log(markers);
    // var a = '<div class="marker" style="left:';
    var b = '<div class="marker">';
    for (var i = 0; i < markers.length; i++) {
      var left = markers[i].time / this.duration
      // b = a + left * 100 + '%;">';
      var marker = $(b)
      marker.css({ 'left': left * 100 + '%' })
      // console.log(b);
      $('.vjs-progress-holder').append(marker)
    }
    this.myPlayer.on('play', function () {
      _this.listenTime(globalTmp.last)
    })
    this.myPlayer.on('pause', function () {
      _this.stopTimer1(globalTmp.last)
    });
    this.markers.sort((a, b) => {
      return a.time - b.time;
    });
    this.markers.push({ time: this.duration + 1 });
  },
  stopTimer1: function () {
    if (this.timer1) { clearInterval(this.timer1) }
  },
  nextTime: function (time) { // 获取下一个时间
    let i = 0;
    for (i = 0; i < this.markers.length; i++) {
      if (this.markers[i].time > time) {
        globalTmp.time = this.markers[i].time;
        return i - 1;
      }
    }

    return -1;
  },
  tp: 0,
  // 监听时间------------------------------------------------------------------监听时间
  listenTime: function (time) {
    if (time < (globalTmp.last - 1)) { // 后退.
      // console.log('后退', time, globalTmp.last);
      this.nextTime(time);
      globalTmp.check = time + 5;
    } else if (time > (globalTmp.last + 1)) { // 前进
      // console.log('前进', time, globalTmp.last);
      this.nextTime(time);
      globalTmp.check = time + 5;
    } else if (time > globalTmp.time) {
      // console.log('设置时间', time, globalTmp.time);
      // time = globalTmp.time;
      // this.myPlayer.pause()
      // this.myPlayer.currentTime(time);
      globalTmp.check = time + 5;
      let i = this.nextTime(time);
      if (i >= 0) this.dialogFun(i);
    }
    // if (globalTmp.check) {
    // if (time > globalTmp.check) {
    // globalTmp.check += 5;
    // if (globalTmp.check > this.myPlayer.cache_.duration) {
    // globalTmp.check = 0;
    // } else {
    // this.myPlayer.currentTime(time + this.tp);
    // }
    // }
    // } else globalTmp.check = 5;
    // if (this.tp) {
    // this.tp = parseInt((this.tp + time - globalTmp.last) * 500) / 1000;
    // } else this.tp = time - globalTmp.last;
    globalTmp.last = time;
  },
  // 执行提问
  dialogFun: function (i) {
    var markers = this.markers
    this.nowObj = i
    // console.log(markers[i].type);
    this.myPlayer.pause()
    this.questionType(markers[i])
  },
  dialog: function (type = 'suc') {
    var d = $('<div class="dialog">')
    if (type == 'err') {
      d.append('错误 <span style="color:red" class="icon-cross"></span>')
    } else if (type == 'suc') {
      d.append('正确 <span style="color:green" class="icon-checkmark"></span>')
    }
    $(".mask").append(d)
    setTimeout(function () {
      d.remove()
    }, 500)
  },
  // 初始化录音-------------------------------------------------------------初始化录音
  canIuseMic: false,
  initMyRecord: function () {
    console.log('当前模式:', this.isApp);
    var _this = this
    if (this.isApp == 'h5') {
      this.myRecord = new EngineEvaluat({
        micAllowCallback: function () {
          _this.canIuseMic = true
        },
        micForbidCallback: function () {
          console.log('麦克风没有被允许');
        },
        playAudioComplete: function (data) {
          console.log('播放完毕');
        },
        playAudioError: function (data) {
          console.log('播放出错');
        },
        engineBackResultDone: function (msg) {
          _this.myRecordResult(JSON.parse(msg));
        },
        engineBackResultFail: function (msg) {
          _this.myRecordResultfail(msg);
        },
        applicationId: '1459219202000001',
        userId: 'any',
        engineLinksAddress: ['trial.cloud.ssapi.cn'],
        engineLinksAddress: ['gate-01.api.cloud.ssapi.cn', 'gate-02.api.cloud.ssapi.cn', 'gate-03.api.cloud.ssapi.cn', 'api.cloud.ssapi.cn', '52.80.61.105', '106.14.179.138', 'trial.cloud.ssapi.cn'],
        permissionUrl: 'http://trial.warrant.ssapi.cn'
      });
    } else if (this.isApp == 'weIos') {
      weChatIOS.weConfig()
    }
  },
  myRecordResultfail(res) {
    console.log(JSON.parse(res));
    // return;
    var _this = this
    var divC = $("<div class='qu-body'>")
    var imgurl = './img/tryagain.png?44'
    divC.append(`<div class='safdsa'>
            <img class='checkImgSize' src="${imgurl}" />
          </div>`)
    var content = $('<div class="content">')
    content.append(divC)
    content.append(`
            <div class="next-wrapp">
              <div class="footer-item"><div class='reListen'></div></div>
              <div class="footer-item"> <div class='reRecord'></div></div>
              <div class="footer-item next-hook"> <div class='next'></div></div>
            </div>
            `);
    $('.mask').html(content)
    $('.reRecord').on('click', function () {
      _this.audio2audio(_this.markers[_this.nowObj])
    });
    checkImgSize();
  },
  setTimeoutLoop: null,
  //开始录音
  recordFun: function (obj) {
    var _this = this
    console.log("开始录音-" + _this.isApp);
    $("button.record").html(`<img class="re-out1" src='./img/recording.png' />`);
    var params = {};
    // 评测类型;
    params.coreType = obj.coreType;
    params.refText = $.trim(obj.refText); // defaultTime
    if (params.refText) {
      if (_this.isApp == 'h5') { //普通浏览器环境
        if (_this.canIuseMic) {
          _this.myRecord.startRecord(params);
          setTimeoutLoop = setTimeout(function () {
            _this.stopRecordFun();
          }, defaultTime(params.refText) + 1000);
          return;
        } else {
          console.log("麦克风不能使用！")
          _this.goOn()
        }
      } else if (_this.isApp == 'IOSapp') {
        console.log('app内调用录音')
        nativeIOS.startRecord(params, function (res) {
          // js逻辑处理
          if (res.errorCode) {
            videosObj.myRecordResultfail();
          } else {
            var dd = {
              result: {
                overall: res.overallScore
              }
            }
            videosObj.myRecordResult(dd)
          }
        })
      } else if (_this.isApp == 'weIos') {
        weChatIOS.startRecord();
      } else if (_this.isApp == 'androidApp') {
        nativeAndroid.startRecord(params)
      } else if (_this.isApp == 'u3dApp') {
        console.log('U3D内调用录音');
        nativeU3D.startRecord(params)
      }
    } else {
      console.log("录音文字为空");
    }
    // checkImgSize();
  },
  //停止录音
  stopRecordFun: function () {
    var _this = this
    clearTimeout(_this.setTimeoutLoop)
    console.log("停止录音，开始检测")
    // $(".record-icon").attr("class", 'record-icon icon-spin icon-spinner6')
    if (this.isApp == 'h5') {
      this.myRecord.stopRecord();
    } else if (_this.isApp == 'weIos') {
      weChatIOS.stopRecord()
    } else if (_this.isApp == 'u3dApp') {
      console.log('U3D内调用停止录音')
      nativeU3D.stopClickRecord()
    }
    checkImgSize();
  },
  // 录音完毕
  myRecordResult: function (recordResult) {
    console.log('myRecordResult');
    var _this = this
    // 如果为h5播放初始录音
    if (_this.isApp == 'h5') {
      var audioUrl = 'https://files.cloud.ssapi.cn/' + recordResult.applicationId + '/' + recordResult.recordId + ".mp3"
      _this.myRecord.loadAudio(audioUrl)
    }
    var point = recordResult.result.overall
    var divC = $("<div class='qu-body'>")
    var imgurl = ''
    if (80 <= point) {
      imgurl = './img/excelent.png'
      $("#excelentAudio")[0].play()
    } else if (60 <= point && point < 80) {
      imgurl = './img/great.png'
      $("#greatAudio")[0].play()
    }
    else if (40 <= point && point < 60) {
      imgurl = './img/goodjob.png'
      $("#goodjob")[0].play()
    } else if (20 <= point && point < 40) {
      imgurl = './img/notgood.png'
      $("#tryaginAudio")[0].play()
    }
    else if (0 <= point && point < 20) {
      imgurl = './img/tryagain.png'
      $("#tryaginAudio")[0].play()
    }
    divC.append(`<div class='safdsa' style="">
            <img class='checkImgSize' src="${imgurl}" />
          </div>`)
    var content = $('<div class="content">')
    content.append(divC);
    console.log(123);
    content.append(`
            <div class="next-wrapp" >
            <div class="footer-item"><div class='reListen'></div></div>
            <div class="footer-item"> <div class='reRecord'></div></div>
            <div class="footer-item next-hook"> <div class='next'></div></div>
            </div>
            `);
    $('.mask').html(content)
    $('.reRecord').on('click', function () { //重新录音
      _this.audio2audio(_this.markers[_this.nowObj])
    })
    $(".next-hook").on('click', function () { //点击继续
      _this.goOn()
    })
    $(".reListen").on("click", function () {
      // 播放录音
      if (_this.isApp == 'h5') {
        _this.myRecord.playAudio()
      } else if (_this.isApp == 'IOSapp') {
        nativeIOS.playRecordFile()
      } else if (_this.isApp == 'weIos') {
        weChatIOS.startPlay()
      } else if (_this.isApp == 'androidApp') {
        nativeAndroid.playRecordFile()
      } else if (_this.isApp == 'u3dApp') {
        nativeU3D.playRecordFile()
      }
    })
    checkImgSize();
  }, //录音相关 end --------------------------------------------------------录音相关 end
  init: function (Dom) {
    let v = $(Dom)[0];
    this.initMyRecord();
    this.myPlayer = videojs(v);
    var _this = this;

    this.myPlayer.on('loadedmetadata', () => {
      this.duration = this.myPlayer.duration();
      this.addMarkers();
      $(".video-js").append("<div class='mask' style='display:none'></div>")
    });

    // this.myPlayer.on('canplay', () => {
    //   console.log('加载完毕');
    // });

    this.myPlayer.on("firstplay", function () {
      videosObj.myPlayer.muted(true);
      videosObj.myPlayer.muted(false);
      hideProgressBar();
    });

    this.myPlayer.width(window.innerWidth); // 设置宽度
    this.fmClass = $('#vc').children()[0].className;

    this.myPlayer.on('ended', () => {
      $('#vc').children()[0].className = this.fmClass;
      this.sfp = true;
      console.log('播放完毕');
      videoEnded();
      if (navigator.userAgent.toLowerCase().indexOf('unity3d') >= 0) window.location.href = "uniwebview://videoFinish";
    });

    this.myPlayer.on('timeupdate', () => {
      if (this.fpClass) {
        if (this.sfp) {
          this.sfp = false;
          $('#vc').children()[0].className = this.fpClass;
        }
      } else {
        this.fpClass = $('#vc').children()[0].className;
        this.sfp = true;
      }
      this.listenTime(this.myPlayer.cache_.currentTime);
    });
    // console.log($('#vc').height(), window.innerHeight);
    let h = $('#vc').height();
    // this.myPlayer.width(window.innerWidth);
    if (navigator.userAgent.toLowerCase().indexOf('unity3d') >= 0) this.myPlayer.height(window.innerHeight);
    else if ($('#vc').height() > window.innerHeight) this.myPlayer.height(window.innerHeight);
    // console.log($('#vc').height(), window.innerHeight, $('#vc'), $('#vc').height());
    $('#vc').removeClass('none');
    $('#loading').hide();
    globalTmp.time = this.markers[0].time;
  }
}
// 隐藏进度条
function hideProgressBar() {
  if (progressBar) {
    $('.vjs-control-bar').css({ "display": "flex" })
  } else {
    $('.vjs-control-bar').hide()
  }
}
function defaultTime(refText) {
  return 2000 + refText.trim().split(' ').length * 600;
}
$(document).bind("keydown", function (event) {
  if (videosObj && videosObj.myPlayer && videosObj.myPlayer.cache_) {
    var currentTime = videosObj.myPlayer.cache_.currentTime;
    if ($('.mask').css('display') == 'none') {
      if (event.which == 39) {
        console.log(currentTime + 0.1)
      } else if (event.which == 37) {
        console.log(currentTime - 0.1)
      } else if (event.which == 32) {
        if (videosObj.myPlayer.paused) {
          videosObj.myPlayer.play()
        } else {
          videosObj.myPlayer.pause()
        }
      }
    }
  }
})

//调用app方法
function setupWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
  if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
  window.WVJBCallbacks = [callback];
  var WVJBIframe = document.createElement('iframe');
  WVJBIframe.style.display = 'none';
  WVJBIframe.src = 'https://__bridge_loaded__';
  document.documentElement.appendChild(WVJBIframe);
  setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
}
// 判断是否在app中
function isApp() {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf('native_ios') > -1) { return 'IOSapp' }
  if (ua.indexOf('android_inner_broser') > -1) { return 'androidApp' }
  if (ua.indexOf('native_unity3d') > -1) { return 'u3dApp' }
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return 'weIos'
  }
  return 'h5'
}
//app录音返回
function JS_ResponseEvaluateResult(res) {
  if (res.errorCode) {
    videosObj.myRecordResultfail();
  } else {
    var dd = {
      result: {
        overall: res.overallScore
      }
    }
    videosObj.myRecordResult(dd)
  }
}
// 调用安卓方法
function JS_ResponseEvaluateResult_Android(errorCode, overallScore, msg) {
  console.log('android回调js结果', errorCode, overallScore, msg)
  nativeAndroid.stopRecord(errorCode, overallScore, msg)
}
function JS_ResponseEvaluateResult_U3D(errorCode, overallScore, msg) {
  console.log('U3D执行js', errorCode, overallScore, msg)
  nativeU3D.stopRecord(errorCode, overallScore, msg);
  checkImgSize();

}


function myFun() {
  var ws = new WebSocket('wss://api.cloud.ssapi.cn/en.sent.score');
}

function checkImgSize(params) {
  $('.playAudio').attr("disabled", false);
  let obj = $('.checkImgSize');
  let sum = 100; // 10秒
  if (params && params.obj) {
    sum = params.sum;
    obj = params.obj;
  }
  let i = 0;
  let c = 0;
  let f = 0;
  for (i = 0; i < obj.length; i++) {
    c = obj.eq(i); f = c.parent();
    c = { obj: c, w: c.width(), h: c.height() };
    f = { obj: f, w: f.width(), h: f.height() };
    if (f.w && f.h) {
      console.log(c, f);
      if (c.w == f.w) c.obj.height(f.h);
      else if (c.h == f.h) c.obj.width(f.w);
    } else if (sum) {
      setTimeout((a) => {
        checkImgSize(a);
      }, 100, { obj: c.obj, sum: sum - 1 });
    }
  }
}
function ImgHf() {
  let ai = $('.answer-item');
  let p = $('.qu-body');
  let i = $('.imgB');
  ai.css('flex-grow', '1');
  i.eq(0).load(() => {

    let o = i[0].naturalWidth / i[0].naturalHeight;
    let c = i.width() / i.height();
    if (o > c) {
      // let h = i.height() / o;

      ai.height(ai.width() / o);
    }

    ai.css('flex-grow', '0');
    // naturalWidth
    // console.log(o, c, ai.width(), i.width());
  });
  // i.height('90%');
  // if (p.height() > ai.height()) {
  //   ai.css('height', '100%');
  //   $('.answer-item-hook').css('height', '100%');
  // }
}
function removeFly(param, callback, left) {
  if (typeof left == 'undefined') {
    let s = param.siblings().length;
    let l = param.prevAll();
    let r = param.nextAll();
    removeFly(l, () => {
      s -= l.length;
      if (s < 1) callback();
    }, true);
    removeFly(r, () => {
      s -= r.length;
      if (s < 1) callback();
    }, false);
    return;
  }
  let obj = [];
  let i = param.length;
  if (!Array.isArray(param)) {
    for (i = 0; i < param.length; i++) {
      obj.unshift(param[i]);
    }
    param = obj;
  }
  if (!param.length) return;
  obj = $(param[0]);
  let w = obj.offset().left + obj.width();
  let x = w / 20;
  if (left) x *= -1;
  i = 0;
  let handle = setInterval(() => {
    if (Math.abs(i * x) < w) {
      i++
      obj.css('left', i * x + 'px');
    } else {
      clearInterval(handle);
      if (param.length > 1) removeFly(param.slice(1), callback, left, x / 2);
      else callback();
    }
  }, 10);
}
$.fn.bc = function () {
  let rgb = $(this).css('background-color');
  if (rgb.substr(0, 1) != '#') {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    if (!rgb) return;
    function hex(x) {
      return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    rgb = "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
  }
  return rgb.toUpperCase();
}
function ElementShine(param, callback, sum = 3 * 2, inherit = false) {
  // param = param.children().eq(0);
  let s = '#FCFF00';
  let t = 0;
  let handle = setInterval(() => {
    sum--;
    if (sum % 2) {
      t = s;
    } else {
      // t = 'inherit';
      t = '';
    }
    param.css('background-color', t);
    if (!sum) {
      clearInterval(handle);
      callback();
    }
  }, 150);
}
function type7right(param, callback) {
  let shine = $(param);
  ElementShine(shine, () => {
    removeFly(shine, () => {
      shine.siblings().remove();
      shine.removeAttr('style');
      let i = shine.children().eq(0)[0];
      let o = i.naturalWidth / i.naturalHeight;
      i = 70;
      // let t = 0;
      let handle = setInterval(() => {
        if (i < 80) {
          i++;
          shine.height(i + '%');
          shine.width(o * shine.height());
        } else {
          // console.log(shine);
          clearInterval(handle);
          // t = shine.height();
          shine.width(o * shine.height());
          // shine.height(t);
          // shine.attr('id', o);
        }
      }, 20);
      if (callback) callback();
    })
  });
}
function type7err(param, callback) {
  let obj = $(param);
  ElementShine(obj, () => {
    if (callback) callback();
    // obj.children().eq(0).css('filter1');
    obj.children().eq(0).css('-webkit-filter', 'brightness(50%)');
    setTimeout(() => {
      // obj.css('background-color', 'inherit');
      // obj.children().eq(0).removeClass('filter1');
      obj.children().eq(0).css('-webkit-filter', '');
    }, 500);
  })
}